package org.glut.gateway.config;

import org.springframework.cloud.gateway.filter.factory.GatewayFilterFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

@Configuration
public class GatewayConfiguration {

    /**
     * IP限流：初始化用户 IP 作为限流key
     * @return
     */
    // @Bean //Bean Name: hostAddrKeyResolver
    // public KeyResolver hostAddrKeyResolver() {
    //     return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()); //.getHostName()
    // }

    /**
     * 用户限流: 初始化用户名作为限流key
     * @return
     */
    // @Bean
    // public KeyResolver userKeyResolver() {
    //     return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    // }

    /**
     * 接口限流：初始化接口路径作为限流key
     * @return
     */
    @Bean //Bean Name: apiKeyResolver
    KeyResolver apiKeyResolver() {
        System.err.println("\n=============================>\napiKeyResolver\n==============================");
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

  /*  @Bean
    public RateLimiter rateLimiter() {
        RateLimiterConfig config = RateLimiterConfig.custom()
            .limitRefreshPeriod(Duration.ofSeconds(1))
            .limitForPeriod(1)
            .timeoutDuration(Duration.ofMillis(500))
            .build();
        System.err.println("\n=============================>\nrateLimiter\n==============================");
        return RateLimiter.of("gatewayRateLimiter", config);
    }*/

    @Bean
    public GatewayFilterFactory redisRateLimiterGatewayFilterFactory() {
        System.err.println("\n=============================>\nredisRateLimiterGatewayFilterFactory\n==============================");
        return new RedisRateLimiterGatewayFilterFactory();
    }
}